<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */

namespace App\Common\Controller;

use App\Common\Constants\ErrorCode;
use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Psr\Container\ContainerInterface;

/**
 * Class AbstractController
 * @package App\Common\Controller
 */
abstract class AbstractController
{
    const GUARD_NAME = 'admin';
    /**
     * @Inject
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @Inject
     * @var RequestInterface
     */
    protected $request;

    /**
     * @Inject
     * @var ResponseInterface
     */
    protected $response;

    /**
     * 请求成功
     *
     * @param        $data
     * @param string $message
     * @param int $total
     * @return array
     */
    public function success($data, $message = 'success', $total = 0)
    {
        $code = $this->response->getStatusCode();
        return ['msg' => $message, 'code' => $code, 'total' => $total, 'data' => $data];
    }

    /**
     * 请求失败.
     *
     * @param $code
     * @param string $message
     *
     * @return array
     */
    public function failed($code, ?string $message = null)
    {
        if (!$message) {
            $message = ErrorCode::getMessage($code);
        }
        return ['msg' => $message, 'code' => $code, 'data' => ''];
    }

    /**
     * 返回结果
     *
     * Author: mengchenchen
     * Created_at: 2021/1/6 0006 13:37
     * Updated_at: 2021/1/6 0006 13:37
     *
     * @param array $ret
     * @return array
     */
    public function resultFormat(array $ret): array
    {
        $code = $ret['code'] ?? 500;
        if ($code) {
            return $this->failed($code, $ret['msg'] ?? '');
        }
        return $this->success($ret['data'] ?? [], 'success', $ret['total'] ?? 0);
    }

    /**
     * @return array|object|null
     */
    public function validated()
    {
        return $this->request->getParsedBody();
    }

//    public function
}
